<template>
	<div>
		<Bread>
			<template v-slot:title>
				<el-breadcrumb-item v-for="(item, index) in titleList" :key="index"> {{ item }}</el-breadcrumb-item>
			</template>
		</Bread>

		<el-card>
			<el-alert title="警注意：只允许为第三级分类设置相关参数！" type="warning" :closable="false"> </el-alert>


			<!-- 选择分类组件 -->
			<el-row class="bottom">
				<el-col :span="3">
					<span>选择商品分类：</span>
				</el-col>
				<el-col :span="4">

					<el-cascader v-model="selected" :options="list" :props="cateProps" @change="handleChange" :show-all-levels="false"></el-cascader>

				</el-col>
			</el-row>

			<!-- tab组件 -->
			<el-tabs v-model="activeName" @tab-click="handleClick">
				<el-tab-pane label="动态参数" name="many">
					<el-row class="left">
						<!-- 添加属性 -->

						<el-button type="primary" plain :disabled="isBoolean" @click="addAttribute" class="bottom">添加属性</el-button>

					</el-row>

					<!-- 动态数据表格 -->
					<el-table :data="manyList" style="width: 100%" stripe border>
						<el-table-column type="expand">
							<template v-slot="scope">
								<!-- tag标签 -->
								<el-tag type="success" v-for="(item, index) in scope.row.attr_vals" :key="index" closable @close="handleClose(scope.row, index)">

									{{ item }}
								</el-tag>
								<!-- 添加文本框 -->
								<el-input
									class="input-new-tag"
									v-if="scope.row.inputVisible"
									v-model="scope.row.inputValue"
									ref="saveTagInput"
									size="mini"
									@keyup.enter.native="handleInputConfirm(scope.row)"
									@blur="handleInputConfirm(scope.row)"
								>
								</el-input>

								<el-button
									v-else
									class="button-new-tag"
									size="small"
									@click="showInput(scope.row)"
									>+ New Tag</el-button
								>
							</template>
						</el-table-column>
						<el-table-column type="index" width="50"> </el-table-column>
						<el-table-column prop="attr_name" label="参数名称">
						</el-table-column>

						<el-table-column label="操作">
							<template v-slot="scope">
								<div class="center">
									<div class="btn">

										<el-button
											type="primary"
											icon="el-icon-edit"
											@click="updateData(scope.row)"
										>
											编辑</el-button
										>

										<el-button
											type="danger"
											icon="el-icon-delete"
											@click="deleteAttribute(scope.row)"
										>
											删除</el-button
										>

									</div>
								</div>
							</template>
						</el-table-column>
					</el-table>
				</el-tab-pane>
				<el-tab-pane label="静态参数" name="only">
					<el-row class="left">
						<!-- 添加属性 -->

						<el-button
							type="primary"
							plain
							:disabled="isBoolean"
							@click="addAttribute"
							class="bottom"
							>添加属性</el-button
						>

					</el-row>

					<!-- 静态数据表格 -->
					<el-table :data="onlyList" style="width: 100%" stripe border>

							<el-table-column type="expand">
							<template v-slot="scope">
								<!-- tag标签 -->
								<el-tag
									type="success"
									v-for="(item, index) in scope.row.attr_vals"
									:key="index"
									closable
									@close="handleClose(scope.row, index)"
								>

									{{ item }}
								</el-tag>
								<!-- 添加文本框 -->
								<el-input
									class="input-new-tag"
									v-if="scope.row.inputVisible"
									v-model="scope.row.inputValue"
									ref="saveTagInput"
									size="mini"
									@keyup.enter.native="handleInputConfirm(scope.row)"
									@blur="handleInputConfirm(scope.row)"
								>
								</el-input>

								<el-button
									v-else
									class="button-new-tag"
									size="small"
									@click="showInput(scope.row)"
									>+ New Tag</el-button
								>
							</template>
						</el-table-column>
						<el-table-column type="index" width="50"> </el-table-column>
						<el-table-column prop="attr_name" label="参数名称">
						</el-table-column>

						<el-table-column label="操作">
							<template v-slot="scope">
								<div class="center">
									<div class="btn">

										<el-button type="primary" icon="el-icon-edit" @click="updateData(scope.row)"> 编辑</el-button>

										<el-button type="danger" icon="el-icon-delete" @click="deleteAttribute(scop.row)"> 删除</el-button>

									</div>
								</div>
							</template>
						</el-table-column>
					</el-table>
				</el-tab-pane>
			</el-tabs>
		</el-card>

		<!-- 添加属性对话框 -->

		<el-dialog :title="title" :visible.sync="dialogVisible" width="30%" :show-close="false">
			<!-- 表单验证 -->
			<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">

				<el-form-item label="参数名称" prop="name">
					<el-input v-model="ruleForm.name"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisibles">取 消</el-button>
				<el-button type="primary" @click="dialogVisibled">确 定</el-button>
			</span>
		</el-dialog>

		<!-- 编辑属性对话框 -->

		<el-dialog
			:title="title"
			:visible.sync="updatedialogVisible"
			width="30%"
			:show-close="false"
		>
			<!-- 表单验证 -->
			<el-form
				:model="ruleForm"
				:rules="rules"
				ref="ruleForms"
				label-width="100px"
				class="demo-ruleForm"
			>

				<el-form-item label="参数名称" prop="updatename">
					<el-input v-model="ruleForm.updatename"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="UpdatedialogVisibles">取 消</el-button>

				<el-button type="primary" @click="UpdatedialogVisibled"
					>确 定</el-button
				>

			</span>
		</el-dialog>
	</div>
</template>

<script>
import Bread from '../../components/Bread.vue'
export default {
	name: 'Params',
	components: {
		Bread,
	},
	data() {
		return {
			count: 0,
			ruleForm: {
				name: '',
				updatename: '',
			},
			rules: {
				name: [{ required: true, message: '属性不能为空', trigger: 'blur' }],
				updatename: [{ required: true, message: '属性不能为空', trigger: 'blur' }],

			},
			dialogVisible: false,
			updatedialogVisible: false,
			activeName: 'many',
			cateProps: {
				value: 'cat_id',
				label: 'cat_name',
				children: 'children',
				expandTrigger: 'hover',
			},
			list: [],
			selected: [],
			updateAttar_id: '',
			updateCat_id: '',
			titleList: ['商品列表', '参数列表'],
			manyList: [], // 动态数据
			onlyList: [], // 静态数据
		}
	},
	mounted() {},
	computed: {
		isBoolean: {
			get() {
				return this.selected.length == 3 ? false : true
			},
		},
		title: {
			get() {
				return this.activeName == 'many' ? '动态属性' : '静态属性'
			},
		},
	},
	created() {
		this.getData()
	},
	watch: {
		selected(newValue) {

			if (newValue.length <= 2) {
				this.$message.error('当前不是第三级分类！')
			}
		},
	},
	methods: {
		// tag 删除 按钮
		handleClose(row, index) {
			row.attr_vals.splice(index, 1)


			this.$http
				.put(`categories/${row.cat_id}/attributes/${row.attr_id}`, {
					attr_sel: this.activeName,
					attr_name: row.attr_name,
					attr_vals: row.attr_vals.join(' '),
				})
				.then(res => {
					let { meta } = res.data

					if (meta.status != 200) {
						this.$message.error(meta.msg)
					}
				})
				.catch(error => {
					console.log(error.message)
				})
		},
		// 添加tag标签 点击回车或者失去焦点输入框
		handleInputConfirm(row) {
			if (row.inputValue.trim().length == 0) {
				row.inputValue = ''
				row.inputVisible = false
				return
			}
			row.attr_vals.push(row.inputValue.trim())
			row.inputValue = ''
			row.inputVisible = false
			this.$http
				.put(`categories/${row.cat_id}/attributes/${row.attr_id}`, {
					attr_sel: this.activeName,
					attr_name: row.attr_name,
					attr_vals: row.attr_vals.join(' '),
				})
				.then(res => {

					let { meta } = res.data

					if (meta.status != 200) {
						this.$message.error(meta.msg)
					}
				})
				.catch(error => {
					console.log(error.message)
				})
		},
		// 添加tag标签点击按钮
		showInput(row) {
			row.inputVisible = true
			this.$nextTick(() => {

				this.$refs.saveTagInput.$refs.input.focus()
			})
		},
		// 删除属性按钮

		deleteAttribute(data) {
			this.updateAttar_id = data.attr_id
			this.updateCat_id = data.cat_id
			this.$confirm('是否删除删除?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})

				.then(() => {
					this.$http.delete(`categories/${this.updateCat_id}/attributes/${this.updateAttar_id}`).then(res => {
						let { meta } = res.data
						if (meta.status != 200) return this.$message.error('删除失败！')
						this.getAttribut()
						this.$message({
							type: 'success',
							message: '删除成功！',
						})
					})

				})
				.catch(err => {
					console.log(err.message)
				})
		},

		// 编辑按钮
		updateData(data) {
			this.updatedialogVisible = true


			this.ruleForm.updatename = data.attr_name
			this.updateAttar_id = data.attr_id
			this.updateCat_id = data.cat_id
		},
		// 编辑对话框取消
		UpdatedialogVisibles() {
			this.updatedialogVisible = false
		},
		// 编辑对话框确定
		UpdatedialogVisibled() {
			this.$refs.ruleForms.validate(boolean => {
				if (!boolean) return
				this.$http

					.put(`/categories/${this.updateCat_id}/attributes/${this.updateAttar_id}`, {
						attr_name: this.ruleForm.updatename,
						attr_sel: this.activeName,
					})

					.then(res => {
						let { meta } = res.data
						if (meta.status != 200) return this.$message.error('更新失败！')
						this.getAttribut()
						return this.$message({
							message: '更新数据成功！',
							type: 'success',
						})
					})
					.catch(err => {
						console.log(err.message)
					})
			})
			this.updatedialogVisible = false
		},
		// 添加属性对话框 取消
		dialogVisibles() {
			this.$refs.ruleForm.resetFields()
			this.dialogVisible = false
			this.$refs.ruleForm.validate
		},
		// 添加属性对话框 确认
		dialogVisibled() {
			this.$refs.ruleForm.validate(boolean => {
				if (!boolean) return
				this.$http
					.post(`/categories/${this.selected[2]}/attributes`, {
						attr_name: this.ruleForm.name,
						attr_sel: this.activeName,
					})
					.then(res => {
						let { meta } = res.data

						if (meta.status != 201) return this.$message.error('获取参数失败！')
						this.getAttribut()
						return this.$message({
							type: 'success',
							message: '添加属性成功',
						})
					})
					.catch(err => {
						console.log(err.message)
					})
			})
			this.$refs.ruleForm.resetFields()
			this.dialogVisible = false
		},
		// 添加属性
		addAttribute() {
			this.dialogVisible = true
		},
		// 添加分类
		dynamic() {
			this.$http.post(`/categories/${this.selected[2]}/attributes`, {
				attr_name: '',
				attr_sel: this.activeName,
				attr_vals: '',
			})
		},
		// 属性类表数据获取
		getAttribut() {
			if (this.selected.length == 2) {
				this.selected = []
				this.manyList = []
				this.onlyList = []
			} 

			this.$http
				.get(`categories/${this.selected[2]}/attributes`, {
					params: {
						sel: this.activeName,
					},
				})
				.then(res => {
					let { data, meta } = res.data

					if (meta.status != 200) {
						this.$message.error('获取参数失败！')
					}

					data.forEach(item => {
						item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
						item.inputVisible = false
						item.inputValue = ''
					})

					if (this.activeName == 'many') {
						this.manyList = data
						return
					}
					this.onlyList = data
				})
				.catch(error => {
					console.log(error.message)
				})
		},
		// 级联选择框选中时调用
		handleChange() {

			this.getAttribut()
		},
		//tab栏切换的时候调用
		handleClick() {
			if (this.selected.length !== 0) {
				this.$http
					.get(`categories/${this.selected[2]}/attributes`, {
						params: {
							sel: this.activeName,
						},
					})
					.then(res => {
						let { data, meta } = res.data
						data.forEach(item => {
							item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
							item.inputVisible = false
							item.inputValue = ''
						})

						if (meta.status != 200) {
							this.$message.error('获取参数失败！')
						}
						if (this.activeName == 'many') {
							this.manyList = data
							return
						}
						this.onlyList = data
					})
					.catch(error => {
						console.log(error.message)
					})
			}
		}, // 级联选择框 所需要的 类表数据
		getData() {
			this.$http
				.get('/categories')
				.then(res => {
					let { data, meta } = res.data
					if (meta.status != 200) {
						this.$message.error('获取参数失败！')
					}
					this.list = data
				})
				.catch(error => {
					console.log(error.message)
				})
		},
	},
}
</script>
<style scoped>
.el-row {
	margin-top: 20px;
}
.el-col-3 {
	margin-top: 9px;
}
.left {
	float: left;
}
.btn {
	width: 100%;
	height: 100%;
	display: flex;
	justify-content: space-around;
}
.bottom {
	margin-bottom: 20px;
}
.center {
	width: 210px;
	margin: auto;
}
.el-tag {
	margin: 0 15px;
}
.input-new-tag {
	width: 120px;
}
</style>
